using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CR.Application.DTOs;
using CR.Application.Interfaces;
using CR.ErrorCode;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CR.API.Controllers
{
    /// <summary>
    /// 产品检验报告控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ProductInspectionReportController : ControllerBase
    {
        private readonly IProductInspectionReportService _reportService;
        private readonly IWebHostEnvironment _environment;
        private readonly ILogger<ProductInspectionReportController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="reportService">产品检验报告服务</param>
        /// <param name="environment">Web环境</param>
        /// <param name="logger">日志记录器</param>
        public ProductInspectionReportController(
            IProductInspectionReportService reportService,
            IWebHostEnvironment environment,
            ILogger<ProductInspectionReportController> logger)
        {
            _reportService = reportService ?? throw new ArgumentNullException(nameof(reportService));
            _environment = environment ?? throw new ArgumentNullException(nameof(environment));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 获取指定溯源码的所有检验报告
        /// </summary>
        /// <param name="traceabilityCode">溯源码</param>
        /// <returns>检验报告列表</returns>
        [HttpGet("{traceabilityCode}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> GetByTraceabilityCode(string traceabilityCode)
        {
            try
            {
                var result = await _reportService.GetByTraceabilityCodeAsync(traceabilityCode);
                return result.Code == ApiEnums.Success ? Ok(result) : StatusCode((int)result.Code, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取溯源码 {traceabilityCode} 的检验报告时出错");
                return StatusCode(500, ApiResult.Fail(ApiEnums.SystemError, $"获取检验报告失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取指定ID的检验报告
        /// </summary>
        /// <param name="id">报告ID</param>
        /// <returns>检验报告</returns>
        [HttpGet("detail/{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                var result = await _reportService.GetByIdAsync(id);
                return result.Code == ApiEnums.Success ? Ok(result) : StatusCode((int)result.Code, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取检验报告ID {id} 时出错");
                return StatusCode(500, ApiResult.Fail(ApiEnums.SystemError, $"获取检验报告失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 添加产品检验报告
        /// </summary>
        /// <param name="traceabilityCode">溯源码</param>
        /// <param name="file">报告图片文件</param>
        /// <returns>添加结果</returns>
        [HttpPost("{traceabilityCode}/upload")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> AddReport(string traceabilityCode, IFormFile file)
        {
            try
            {
                var result = await _reportService.AddReportAsync(traceabilityCode, file, _environment.WebRootPath);
                return result.Code == ApiEnums.Success ? Ok(result) : StatusCode((int)result.Code, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"为溯源码 {traceabilityCode} 添加检验报告时出错");
                return StatusCode(500, ApiResult.Fail(ApiEnums.SystemError, $"添加检验报告失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 删除产品检验报告
        /// </summary>
        /// <param name="id">报告ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> DeleteReport(int id)
        {
            try
            {
                var result = await _reportService.DeleteReportAsync(id);
                return result.Code == ApiEnums.Success ? Ok(result) : StatusCode((int)result.Code, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除检验报告ID {id} 时出错");
                return StatusCode(500, ApiResult.Fail(ApiEnums.SystemError, $"删除检验报告失败: {ex.Message}"));
            }
        }
    }
} 